package com.example.bingobox.ui.invoke;

import android.app.Application;
import android.os.Environment;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.bingobox.model.TodoBox;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class InvokeViewModel extends AndroidViewModel {
    private final MutableLiveData<List<TodoBox>> todoBoxes;
    private final Gson gson;

    public InvokeViewModel(Application application) {
        super(application);
        todoBoxes = new MutableLiveData<>(new ArrayList<>());
        gson = new Gson();
        loadTodoBoxes();
    }

    private void loadTodoBoxes() {
        File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
        File todoboxFile = new File(dataDir, "todobox.json");
        
        try (FileReader reader = new FileReader(todoboxFile)) {
            Type type = new TypeToken<Map<String, Object>>(){}.getType();
            Map<String, Object> data = gson.fromJson(reader, type);
            
            if (data.containsKey("todoBoxes")) {
                Type todoBoxType = new TypeToken<List<TodoBox>>(){}.getType();
                List<TodoBox> todoBoxList = gson.fromJson(gson.toJson(data.get("todoBoxes")), todoBoxType);
                todoBoxes.setValue(todoBoxList);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public LiveData<List<TodoBox>> getTodoBoxes() {
        return todoBoxes;
    }
} 